#include "Buffer.h"
#include "socketinclude.h"
#include <iostream>

size_t Buffer::readFileFd(FILE* fpd)
{
    char extrabuf[65535];
    char *ptr = extrabuf;
    int nleft = 65535;
    int nread;
    while((nread = fread(ptr, 1,nleft, fpd)) < 0)
    {
        if(errno == EINTR)
            nread = 0;
        else
            return 0;
    }
    std::cout << "----readFileFd--- " <<extrabuf <<std::endl;
    append(extrabuf, nread);
    return nread;

}
size_t Buffer::readFd(const int fd)
{
    char extrabuf[65535];
    char *ptr = extrabuf;
    int nleft = 65535;
    int nread;
    while((nread = read(fd, ptr, nleft)) < 0)
    {
        if(errno == EINTR)
            nread = 0;
        else 
            return 0;
    }
    append(extrabuf, nread);
    return nread;
}


size_t Buffer::readSocketFd(const int fd)
{
    char extrabuf[65535];
    char *ptr = extrabuf;
    int nleft = 65535;
    int nread;
    while((nread = recv(fd, ptr, nleft, 0)) < 0)
    {
        if(errno == EINTR)
            nread = 0;
        else
            return 0;
    }
    append(extrabuf, nread);
    return nread;
}


void Buffer::sendFd(const int fd)
{
    size_t bytesSent = 0;
    size_t bytesLeft = readableBytes();
    char *ptr = peek();
    while(bytesLeft)
    {
        if((bytesSent = send(fd, ptr, bytesLeft, 0))< 0)
//        if((bytesSent = write(fd, ptr, bytesLeft)) < 0)
        {
            if(bytesSent < 0 && errno == EINTR)
                bytesSent = 0;
            else
                return;
        }
        bytesLeft -= bytesSent;
        ptr += bytesSent;
    } 
    ptr = peek();
    std::cout << "send.............  " << ptr<< std::endl;
    resetBuffer();
}
